const ws = require('ws')
const tool = require('./src/utils/tool')

const wss = new ws.WebSocketServer({
    port: 8083
})

wss.on('connection', socket => {
    console.log('connection');

    socket.on('open', () => {
        console.log('open');
    })

    socket.on('error', (error) => {
        console.log('error', error);
    })

    socket.on('message', data => {
        const message = JSON.parse(data.toString())
        if (message.type === 'login') {
            socket.nickname = message.nickname
            socket.avatar = message.avatar
            Array.from(wss.clients).forEach(client => {
                client.send(JSON.stringify({
                    type: 'clients',
                    clients: Array.from(wss.clients).map(item => {
                        return { nickname: item.nickname, avatar: item.avatar }
                    })
                }))
                if (client === socket) {    // 如果用户是自己
                    socket.send(JSON.stringify({
                        type: 'login-success',
                        name: message.nickname,
                        // clients: wss.clients
                    }))

                } else {    // 如果用户不是自己
                    client.send(JSON.stringify({
                        type: 'user-join',
                        name: message.nickname,
                    }))
                }
            })
        } else if (message.type === 'send') {     // 用户发送信息
            Array.from(wss.clients).forEach(client => {
                if (client === socket) {
                    socket.send(JSON.stringify({
                        type: 'me-send',
                        name: socket.nickname,
                        avatar: socket.avatar,
                        text: message.text,
                        time: tool.sfm(new Date())
                    }))
                } else {
                    client.send(JSON.stringify({
                        type: 'other-send',
                        name: socket.nickname,
                        avatar: socket.avatar,
                        text: message.text,
                        time: tool.sfm(new Date())
                    }))
                }
            })
        } else if (message.type === 'close') {
            Array.from(wss.clients).forEach(client => {
                if (socket !== client) {
                    client.send(JSON.stringify({
                        type: 'other-close',
                        name: socket.nickname
                    }))
                }
            })
        }
    })

    socket.on('close', () => {
        console.log('close', wss.clients);
        // 展示当前在线的用户
        // Array.from(wss.clients).forEach(client => {
        //     client.send(JSON.stringify({
        //         type: 'clients',
        //         clients: Array.from(wss.clients)
        //     }))
        // })

    })
})